package com.weipai.springboot.module.controller;

import com.sun.org.apache.regexp.internal.REUtil;
import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.Exchange;
import com.weipai.springboot.model.Order;
import com.weipai.springboot.model.SaleReturn;
import com.weipai.springboot.model.api.OrderRequest;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.service.FileUploadService;
import com.weipai.springboot.module.service.OrderService;
import com.weipai.springboot.module.service.UserService;
import com.weipai.springboot.module.util.SessionUserUtil;
import org.apache.commons.collections4.Get;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;

/**
 * @author songmengqiang
 * @create 2018-08-24 18:20
 **/
@RestController
public class OrderController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 订单分页查询 根据订单编号,订单状态,时间区间查询订单
     *
     * @param shopId
     * @param status      1未付款，2已付款，2待发货，3待收货，4交易成功 为空表示查询全部 5,交易失败  6 生产中
     * @param orderNumber
     * @param startTime
     * @param endTime
     * @param hasSubList  'Y'-包含子订单信息,其他不包含子订单信息
     * @param page
     * @param size
     * @param draw
     * @return
     */
    @RequestMapping(value = "/order/list", method = RequestMethod.GET)
    public Response getOrderList(
            @RequestParam(value = "shopId", required = false) String shopId,
            @RequestParam(value = "customerId", required = false) String customerId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "orderNumber", required = false) String orderNumber,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "hasSubList", required = false) String hasSubList,
            @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size,
            @RequestParam(value = "keyword", required = false) String keyword,  //关键字搜索
            @RequestParam(value = "modeOfPayment", required = false) Integer modeOfPayment,  //关键字搜索
            @RequestParam(value = "draw", required = false) String draw) {
        Response response = new Response();
        try {
            page = page == null ? 1 : page;
            size = size == null ? 10 : size;
            response = orderService.getOrderList(shopId, customerId, status, orderNumber, startTime, endTime, hasSubList, page, size,keyword,modeOfPayment,draw);
        } catch (Exception e) {
            logger.error("order list with error {}", e);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }
    
    @RequestMapping(value = "/order/list2", method = RequestMethod.GET)
    public Response getOrderList2(
            String shopId,
            String customerId,
            Integer status,
            String orderNumber
    ) {
        System.out.println(orderNumber);
        try {
            Method method = OrderController.class.getMethod("getOrderList2", String.class, String.class, Integer.class, String.class);
            LocalVariableTableParameterNameDiscoverer u =
                    new LocalVariableTableParameterNameDiscoverer();
            String[] param = u.getParameterNames(method);
            System.out.println(Arrays.toString(param));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        return null;
    }


    //更改 订单状态
    @PostMapping("/order/update")
    public Response update(Order order) {
        return orderService.update(order);
    }

    /**
     * 订单详情
     *
     * @param orderNumber
     * @return
     */
    @RequestMapping(value = "/order/getOrderDetail", method = RequestMethod.GET)
    public Response getOrderDetail(@RequestParam("orderNumber") String orderNumber) {
        return orderService.getOrderDetail(orderNumber);
    }

    /**
     * 删除订单
     *
     * @param orderNumber
     * @return
     */
    @RequestMapping("/order/delete")
    public Response deleteOrder(@RequestParam("orderNumber") String orderNumber) {
        return orderService.deleteOrder(orderNumber);
    }

    /**
     * 后台管理页面使用
     *
     * @return
     */
    @RequestMapping("/order/countList")
    public Response getOrderCountList(@RequestParam(value = "time", required = false) String time) {
        return orderService.getOrderCountList(time);
    }

    /**
     * 保存订单
     *
     * @return
     */
    @RequestMapping(value = "/order/save", method = RequestMethod.POST)
    public Response save(@RequestBody OrderRequest orderRequest) {
        return orderService.save(orderRequest);
    }

    /**
     * 退货申请
     * @return
     */
    @PostMapping("/order/returnApplication")
    public Response returnApplication(HttpServletRequest request,
                                      SaleReturn saleReturn,
                                      MultipartFile[] img) {
        Response response = new Response();
        if (img != null && img.length>0) {
            String imgUrl = fileUploadService.saveImgUpload(request, img);
            if (imgUrl.equals("formatError")) {
                response.setCode(RetCode.IMG_FORMAT);
            } else if (imgUrl.equals("sizeover")) {
                response.setCode(RetCode.IMG_SIZE);
            } else if (imgUrl.equals("error")) {
                response.setCode(RetCode.IMG_ERROR);
            } else {
                response = orderService.returnApplication(saleReturn,imgUrl);
            }
        } else {
            response = orderService.returnApplication(saleReturn, "");
        }
        return response;
    }

    /**
     * 换货申请
     * @param exchange
     * @return
     */
    @PostMapping("order/exchangeApplication")
    public Response exchangeApplication(HttpServletRequest request, MultipartFile[] img, Exchange exchange) {
        Response response = new Response();
        if (img != null && img.length>0 ) {
            String result = fileUploadService.saveImgUpload(request, img);
            if (result.equals("formatError")) {
                response.setCode(RetCode.IMG_FORMAT);
            } else if (result.equals("sizeover")) {
                response.setCode(RetCode.IMG_SIZE);
            } else if (result.equals("error")) {
                response.setCode(RetCode.IMG_ERROR);
            } else {
                exchange.setExchangeImg(result);
                response = orderService.exchangeApplication(exchange);
            }
        } else {
            response = orderService.exchangeApplication(exchange);
        }
        return response;
    }

    /**
     * 换货申请的审核
     * @param exchangeNumber：换货订单号
     * @param isAudit：是否审核，1表示同意，-1表示不通过
     * @return
     */
    @GetMapping("order/auditExchange/{exchangeNumber}/{isAudit}")
    public Response auditExchange(@PathVariable("exchangeNumber") String exchangeNumber,
                                  @PathVariable("isAudit") Integer isAudit) {
        return orderService.auditExchange(exchangeNumber, isAudit);
    }

    /**
     * 更改换货订单的状态
     *
     * @return
     */
    @RequestMapping(value = "order/changeExchangeStatus", method = RequestMethod.POST)
    public Response changeExchangeStatus(Exchange exchange) {
        return orderService.changeExchangeStatus(exchange);
    }

    /**
     * 跳转退换货详情页面---------------------------------------------------------------------------------------------
     * @return
     */
    @GetMapping("/order/exchangeGoodsInfo/{orderNumber}/{goodsId}")
    public Response exchangeGoodsInfo(@PathVariable("orderNumber") String orderNumber,
                                      @PathVariable("goodsId") String goodsId) {
        return orderService.exchangeGoodsInfo(orderNumber, goodsId);
    }

    /**
     * 通过orderNumber goodsId  获取订单退换货状态---------------------------------------------------------------------------------------------
     * @return
     */
    @GetMapping("/order/getStatus/{orderNumber}/{goodsId}")
    public Response getStatus(@PathVariable("orderNumber") String orderNumber,
                                      @PathVariable("goodsId") String goodsId) {
        return orderService.getStatus(orderNumber, goodsId);
    }




    /**
     * 审核退货订单
     * @param saleReturnNumber：退货订单单号
     * @param isAudit：状态值1表示同意退货，-1表示拒绝退货 , 2 表示客服确认收货
     * @return
     */
    @GetMapping("/order/auditReturnOrder/{returnNumber}/{isAudit}")
    public Response auditReturnOrder(@PathVariable("returnNumber") String saleReturnNumber, @PathVariable("isAudit") Integer isAudit) {
        return orderService.auditReturnOrder(saleReturnNumber, isAudit);
    }

    /**
     * 退货订单的确认收货
     * @return
     */
    @GetMapping("/order/receivingReturnOrder/{returnNumber}")
    public Response receivingReturnOrder(@PathVariable("returnNumber") String saleReturnNumber) {
        return orderService.receivingReturnOrder(saleReturnNumber);
    }


    /**
     * 换货订单的确认收货
         *exchangeId   换货id
     * @return
     */
    @GetMapping("/order/exchangeReturnOrder/{exchangeId}")
    public Response exchangeReturnOrder(@PathVariable("returnNumber") String exchangeId) {
        return orderService.exchangeReturnOrder(exchangeId);
    }



    /**
     * 获得用户全部的子订单  退换/售后 接口
     *
     * isAfterSale      0:未申请的 ,待发货\交易完成 的订单列表
     *                  1: 申请过的,退换货列表
     * applicationStatus  -1: 按时间段 不可以退换货
     *                     1: 在时间段, 可以退换货
     * @return
     */
    @GetMapping("/order/orderSublistByCustomerId/{page}/{size}/{isAfterSale}")
    public Response orderSublistByCustomerId(@PathVariable("page") Integer page,
                                             @PathVariable("size") Integer size,
                                             @PathVariable("isAfterSale") Integer isAfterSale) {
        return orderService.orderSublistByCustomerId(page, size, isAfterSale);
    }



    /**
     * 获得用户全部的子订单  退换/售后 web端接口----------------------------------------------------------------------------pc web
     *                                           增加搜索接口
     * @return
     */
    @GetMapping("/order/orderSublistByCustomerIdForWeb")
    public Response orderSublistByCustomerIdForWeb(
                                        @RequestParam(value = "page", required = false) Integer page,
                                        @RequestParam(value = "size", required = false) Integer size,
                                        @RequestParam(value = "isAfterSale", required = false) Integer isAfterSale,
                                        @RequestParam(value = "keyword", required = false) String keyword
                                           ) {
        return orderService.orderSublistByCustomerIdForWeb(page, size, isAfterSale,keyword);
    }



    /**
     * 点击售后申请跳转选择售后类型页面
     * @param orderSublistId：子订单的id
     * @return
     */
    @GetMapping("/order/afterTypeInfo/{orderSublistId}")
    public Response afterSaleTypeInfo(@PathVariable("orderSublistId") String orderSublistId) {
        return orderService.afterSaleTypeInfo(orderSublistId);
    }

    /**
     * 确认发货
     * @param orderNumber：订单号
     * @param logisticsCompany：物流公司
     * @param trackingNumber：物流单号
     * @return
     */
    @PostMapping("/order/confirmDelivery")
    public Response confirmDelivery(String orderNumber, String logisticsCompany, String trackingNumber) {
        return orderService.confirmDelivery(orderNumber, logisticsCompany, trackingNumber);
    }

    /**
     * 订单生产中
     * @param orderNumber
     * @return
     */
    @GetMapping("/order/orderGenerate")
    public Response orderGenerate(String orderNumber){
        return orderService.orderGenerate(orderNumber);
    }
    
    /**
     * 退换/售后列表 -  申请记录 -   查看详情
     * 换货订单,传exchangeId,  不传saleReturnId
     * 退换订单,传saleReturnId, 不传exchangeId
     * @param orderNumber
     * @param goodsId
     * @param saleReturnId
     * @param exchangeId
     * @return
     */
    @RequestMapping("/order/geGoodsInfo")
    public Response geGoodsInfo(  @RequestParam(value = "orderNumber")String orderNumber,
                                  @RequestParam(value = "goodsId")String goodsId,
                                  @RequestParam(value = "saleReturnId", required = false)String saleReturnId,
                                  @RequestParam(value = "exchangeId", required = false)String exchangeId
                                ) {
        return orderService.geGoodsInfo(orderNumber, goodsId,saleReturnId,exchangeId);
    }

    /**
     * 退换/售后列表 - 申请记录 - 查看详情 - 填写 运单号
     * @param expressNumber
     * @param saleReturnId
     * @param exchangeId
     * @return
     */
    @RequestMapping("/order/inserExpressInfo")
    public Response inserExpressInfo(@RequestParam(value = "expressNumber")String expressNumber,
                                     @RequestParam(value = "expressCompany")String expressCompany ,
                                     @RequestParam(value = "saleReturnId", required = false) String saleReturnId,
                                     @RequestParam(value = "exchangeId", required = false) String exchangeId
    ) {
        return orderService.inserExpressInfo(expressNumber,expressCompany,saleReturnId,exchangeId);
    }

    /**
     * 后端查询所有的退换货
     * @param isAudit：是否审核   默认为0，1表示同意退货，-1表示拒绝退货
     * @param type：退货/换货订单   1：退货，2换货
     * @return
     */
    @RequestMapping(value = "/order/saleReturn", method = RequestMethod.GET)
    public Response getSaleReturnList(@RequestParam(value = "isAudit") Integer isAudit,
                                      @RequestParam(value = "type", required = false) Integer type,
                                      @RequestParam(value = "page") Integer page,
                                      @RequestParam(value = "size") Integer size,
                                      @RequestParam(value = "draw") String draw,
                                      @RequestParam(value = "search", required = false) String search,
                                      @RequestParam(value = "shopId", required = false) String shopId,
                                      @RequestParam(value = "startTime", required = false) String startTime,
                                      @RequestParam(value = "endTime", required = false) String endTime){
        return orderService.getSaleReturnList(isAudit, type, page, size, draw, search, shopId, startTime, endTime);
    }


    /**
     * 后端查询所有的退货 -- 财务审核页面
     * @return
     */
    @RequestMapping(value = "/order/saleReturnAudit", method = RequestMethod.GET)
    public Response saleReturnAudit(@RequestParam(value = "isAudit") Integer isAudit,
                                      @RequestParam(value = "saleReturnStatus") Integer saleReturnStatus,
                                      @RequestParam(value = "page") Integer page,
                                      @RequestParam(value = "size") Integer size,
                                      @RequestParam(value = "draw") String draw,
                                      @RequestParam(value = "search", required = false) String search,
                                      @RequestParam(value = "shopId", required = false) String shopId,
                                      @RequestParam(value = "startTime", required = false) String startTime,
                                      @RequestParam(value = "endTime", required = false) String endTime){
        return orderService.saleReturnAudit(isAudit, saleReturnStatus, page, size, draw, search, shopId, startTime, endTime);
    }


    /**
     * 退货订单   财务审核  已完成退款   0表示此订单客服未审核，1表示客服待收货，2表示客服已收货  3 表示 付款完成
     * @return
     */
    @GetMapping("/order/receivingReturnOrderAudit/{returnNumber}")
    public Response receivingReturnOrderAudit(@PathVariable("returnNumber") String saleReturnNumber) {
        return orderService.receivingReturnOrderAudit(saleReturnNumber);
    }





    /*  后台管理页面   添加卖家备注
        通过orderId
     */
    @RequestMapping(value = "/order/addNotesByOrderId")
    public Response addNotesByOrderId(String orderId,String notes){
            return  orderService.addNotesByOrderId(orderId,notes);
    }




}
